package com.tina.identify.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.tina.identify.enu.UcloudEnum;
import com.tina.identify.utils.UcloudSignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @Author tina
 * @Time 2020/12/30 上午9:09
 * @Version 1.0
 * @Content 鉴图API
 **/
@Slf4j
@Component
public class IdentifyApi {

    @Value("${ucloud.url}")
    private String ucloudUrl;

    @Value("${ucloud.appId}")
    private String appId;

    @Value("${ucloud.uaicensorPublicKey}")
    private String uaicensorPublicKey;

    @Value("${ucloud.uaicensorPrivateKey}")
    private String uaicensorPrivateKey;

    /**
     * 生成signature，首字母排序
     * 包装参数
     *
     * @param timestamp
     * @param imageUrl
     * @return
     */
    private String getPackageParams(String timestamp, String imageUrl) {
        SortedMap<Object, Object> packageParams = new TreeMap<>();
        packageParams.put("PublicKey", uaicensorPublicKey);
        packageParams.put("ResourceId", appId);
        packageParams.put("Timestamp", timestamp);
        packageParams.put("Url", imageUrl);
        try {
            return UcloudSignUtil.createSign(packageParams, uaicensorPrivateKey);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 包装请求参数
     *
     * @param scenes 场景，场景之间逗号隔开，可选场景： porn - 鉴黄
     * @param method 请求方式，可选方式： url - 传入图片url, file - 传入图片二进制
     * @param url    图片url
     * @return
     */
    private MultiValueMap<String, Object> getRequestPparameter(String scenes, String method, String url) {
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("Scenes", scenes);
        param.add("Method", method);
        param.add("Url", url);
        return param;
    }

    /**
     * 获取请求头参数
     *
     * @param packageParams 生成signature，首字母排序 包装参数
     * @param timestamp     时间戳
     * @return
     */
    private HttpHeaders getHeaders(String packageParams, String timestamp) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("multipart/form-data; charset=UTF-8"));
        headers.set("PublicKey", uaicensorPublicKey);
        headers.set("Signature", packageParams);
        headers.set("ResourceId", appId);
        headers.set("Timestamp", timestamp);
        return headers;
    }

    /**
     * 获取最终返回结果
     *
     * @param param   包装参数
     * @param headers 请求头参数
     * @return
     */
    private JSONObject getResult(MultiValueMap<String, Object> param, HttpHeaders headers) {
        //图片绝对路径
        RestTemplate rest = new RestTemplate();
        HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(param, headers);
        ResponseEntity<String> responseEntity = rest.exchange(ucloudUrl, HttpMethod.POST, httpEntity, String.class);
        String body = responseEntity.getBody();
        JSONObject jsonObject = JSON.parseObject(body);
        return jsonObject;
    }

    /**
     * @param imageUrl
     * @return pass-放行， forbid-封禁， check-人工审核
     * @throws Exception
     */
    public String checkPorn(String imageUrl) {
        String timestamp = System.currentTimeMillis() + "";
        String packageParams = getPackageParams(timestamp, imageUrl);
        if (!StringUtils.isEmpty(packageParams)) {
            JSONObject result = getResult(getRequestPparameter("porn", "url", imageUrl), getHeaders(packageParams, timestamp));
            log.info("jsonObject->{}", result);
            if (result.getInteger("RetCode") == 0) {
                String res = result.getJSONObject("Result").getJSONObject("Porn").getString("Suggestion");
                return res.toUpperCase();
            }else if (result.getInteger("RetCode") == 200451){
                return UcloudEnum.NO.getSuggestion();
            }
        }
        return UcloudEnum.FORBID.getSuggestion();
    }



}
